/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import ejb.BusinessLogicLocal;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Marco
 */
public class ServletCambiaPwd extends HttpServlet {

    @EJB
    private BusinessLogicLocal businessLogic;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        ServletContext sc = getServletContext();
        System.out.println("ENTRO QUA---------------------------");
        try (PrintWriter out = response.getWriter()) {
            HttpSession session = request.getSession();
            String user = (String) session.getAttribute("nomeUtente");
            String password = request.getParameter("nuovapwd");
            String passwordConf = request.getParameter("nuovapwdconf");
            boolean cambiata = true;

            if (!password.equals(passwordConf)) {
                cambiata = false;
            }

            if (!cambiata) {
                //errore le due password non coincidono
            } else {
                //chiama metodo di businessLogic
                StringBuffer hashedpasswd = null;
                try {
                    MessageDigest alg = MessageDigest.getInstance("MD5");
                    alg.reset();
                    alg.update(password.getBytes());
                    byte[] digest = alg.digest();
                    hashedpasswd = new StringBuffer();
                    String hx;
                    for (int i = 0; i < digest.length; i++) {
                        hx = Integer.toHexString(0xFF & digest[i]);
                        //0x03 is equal to 0x3, but we need 0x03 for our md5sum
                        if (hx.length() == 1) {
                            hx = "0" + hx;
                        }
                        hashedpasswd.append(hx);
                    }
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(ServletRegistrazione.class.getName()).log(Level.SEVERE, null, ex);
                }

                boolean result = businessLogic.changePwd(user, hashedpasswd.toString());
                request.setAttribute("risultato", result);
                RequestDispatcher rd = sc.getRequestDispatcher("/cambiaPassword.jsp");
                rd.forward(request, response);
                
                if (result) {
                    out.println("<h1>Password modificata correttamente</h1>");
                    out.println("<h2><a href='homepage.jsp'>Torna alla home</a></h2>");
                } else {
                    out.println("<h1>Errore query</h1>");
                    out.println("<h2><a href='cambiaPassword.jsp'>Riprova</a></h2>");
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
